import { _decorator, Component, director, Node } from "cc"
const { ccclass, property } = _decorator

import Levels from "../../Levels"
import { DataManagerInstance } from "../../Runtime/DataManager"
import { createUINode } from "../../Utils/TileManager"
import EventManager from "../../Runtime/EventManager"
import { EVENT_ENUM } from "../../Enums"
import { PlayerManager } from "../Player/PlayerManager"
import { TileMapManager } from "../Tile/TileMapManager"
import { TILE_WITTH } from "../Tile/TileManager"

@ccclass("BattleManager")
export class BattleManager extends Component {
  level
  stage
  protected onLoad(): void {
    EventManager.on(EVENT_ENUM.NEXT_LEVEL, this.nextLevel, this)
  }
  protected onDestroy(): void {
    EventManager.off(EVENT_ENUM.NEXT_LEVEL, this.nextLevel)
  }
  start() {
    this.generateStage()
    this.initLevel()
  }
  async initLevel() {
    this.clearLevel()
    const level = Levels[`level${DataManagerInstance.levelIndex}`]
    if (level) {
      this.level = level
      DataManagerInstance.mapInfo = level.mapInfo
      DataManagerInstance.maxRowCount = level.mapInfo.length || 0
      DataManagerInstance.maxColumnCount = level.mapInfo[0].length || 0
      await this.generateTileMap()
      this.generatePlayer()
    }
  }
  clearLevel() {
    this.stage.destroyAllChildren()
    DataManagerInstance.reset()
  }
  nextLevel() {
    DataManagerInstance.levelIndex++
    this.initLevel()
  }
  generateStage() {
    this.stage = new Node()
    this.stage.setParent(this.node)
  }
  generateTileMap() {
    return new Promise(resolve => {
      const tileMap = createUINode()
      tileMap.setParent(this.stage)
      const tileMapManager = tileMap.addComponent(TileMapManager)
      tileMapManager.initMap()
      this.adoptPos()
      resolve(1)
    })
  }
  generatePlayer() {
    const player = createUINode()
    player.setParent(this.stage)
    const playerManager = player.addComponent(PlayerManager)

    playerManager.initPlayer()
  }
  adoptPos() {
    const { maxRowCount, maxColumnCount } = DataManagerInstance
    const disX = -0.5 * TILE_WITTH * maxRowCount
    const disY = 0.5 * TILE_WITTH * maxColumnCount
    this.stage.setPosition(disX, disY)
  }
  update(deltaTime: number) {}
}
